﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace MMVoiceComm
{
    internal class ConfigurationManager
    {
        private readonly string commandConfigName =
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) +
            "\\MediaMonkey\\MMVoiceComm\\commands.ini";

        private readonly Dictionary<string, List<string>> commands = new Dictionary<string, List<string>>();

        private readonly string configName = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) +
                                             "\\MediaMonkey\\MMVoiceComm\\config.ini";

        private readonly Dictionary<string, string> configuration = new Dictionary<string, string>();

        public ConfigurationManager()
        {
            if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MediaMonkey\\MMVoiceComm\\"))
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) +
                                          "\\MediaMonkey\\MMVoiceComm\\");
            LoadConfig();
            LoadCommands();
        }

        public Dictionary<string, List<string>> Commands
        {
            get { return commands; }
        }

        public string GetConfigValue(string configName)
        {
            if (configuration.ContainsKey(configName))
            {
                return configuration[configName];
            }
            else
            {
                return "";
            }
        }

        public void SetConfigValue(string configName, string configValue)
        {
                configuration[configName] = configValue;
               
        }

        public void WriteConfig()
        {
            string config = "#MMVoiceComm config file\n#Comments are denoted by the line starting with a # sign\n#for more info see http://mmvoicecomm.codeplex.com/wikipage?title=Configuration%20Options&referringTitle=Documentation\n";
            foreach(KeyValuePair<string,string> kvp in configuration)
            {
                config += kvp.Key + "=" + kvp.Value + "\n";
            }
            try
            {
                File.WriteAllText(configName, config);
            }catch(Exception e)
            {
                Logger.log(e.Message);
            }
        }

        public string[] GetCommandValues(string commandName)
        {
            if (commands.ContainsKey(commandName))
            {
                return Commands[commandName].ToArray();
            }
            else
            {
                return new List<string>().ToArray();
            }
        }

        private void LoadCommands()
        {
            if (!File.Exists(commandConfigName))
                File.WriteAllLines(commandConfigName,
                                   "#MMVoiceComm command file\n#Comments are denoted by the line starting with a # sign\n# layout is 'option=value', you can have multiple values per command option, just say both of them\n# Possible options are play, pause, unpause, test, stop, next, previous, play song, play album, play artist, play genre \nplay song=play song\ntest=test\n#Two of these :)\npause=pause\npause=freeze frame\n#Two of these :)\nunpause=unpause\nunpause=resume\nstop=stop\nnext=next\nprevious=previous\nplay=continue play\nplay artist=play artist\nplay genre=play genre\nplay album=play album"
                                       .Split('\n'));
            string[] fileContents = File.ReadAllLines(commandConfigName);
            foreach (string line in fileContents)
            {
                if (!line.StartsWith("#"))
                {
                    //Is not a comment
                    if (line.Contains("="))
                    {
                        //Is probably a valid line
                        string commandName = line.Substring(0, line.IndexOf('='));
                        string commandValue = line.Substring(line.IndexOf('=') + 1);

                        if (!Commands.ContainsKey(commandName))
                        {
                            Commands[commandName] = new List<string>();
                        }
                        Commands[commandName].Add(commandValue);
                    }
                }
            }
        }

        private void LoadConfig()
        {
            if (!File.Exists(commandConfigName))
                File.WriteAllLines(commandConfigName,
                                   "#MMVoiceComm command file\n#Comments are denoted by the line starting with a # sign\n# layout is 'option=value'\n\n#yes means use binary search + sort to look for duplicates, no means linear search, recommend no\nsortSearch=no\n\n#voice if it's not installed it will default to whatever came up first\nvoice=Acapela Telecom HQ TTS English (US) (Heather 22 kHz)"
                                       .Split('\n'));
            string[] fileContents = File.ReadAllLines(configName);
            foreach (string line in fileContents)
            {
                if (!line.StartsWith("#"))
                {
                    //Is not a comment
                    if (line.Contains("="))
                    {
//Is probably a valid line

                        string optionName = line.Substring(0, line.IndexOf('='));
                        string optionValue = line.Substring(line.IndexOf('=') + 1);

                        //Changeroo
                        if (optionValue.ToLower().Equals("yes")) optionValue = "true";
                        if (optionValue.ToLower().Equals("no")) optionValue = "false";

                        configuration.Add(optionName, optionValue);
                    }
                }
            }
        }

        public void WriteCommands()
        {
            string commandConfig = "#MMVoiceComm command file\n#Comments are denoted by the line starting with a # sign\n# layout is 'option=value', you can have multiple values per command option, just say both of them\n";
            foreach(KeyValuePair<string,List<string>> kvp in commands)
            {
                foreach(string value in kvp.Value)
                {
                    commandConfig += kvp.Key + "=" + value + "\n";
                }
            }
            try {
            File.WriteAllText(commandConfigName, commandConfig);
            }
            catch (Exception e)
            {
                Logger.log(e.Message);
            }
        }

        public void Reload()
        {
            configuration.Clear();
            commands.Clear();
            if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MediaMonkey\\MMVoiceComm\\"))
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) +
                                          "\\MediaMonkey\\MMVoiceComm\\");
            LoadConfig();
            LoadCommands();
        }
    }
}